package server;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import db.DBmanager;

/**
 * Servlet implementation class JoinGame
 */
public class JoinGame extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public JoinGame() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//String userName=(String)request.getSession().getAttribute("userName");
		PrintWriter out=response.getWriter();
		String game_unique_key=request.getParameterValues("gameKey")[0];
		String userName=request.getParameterValues("userName")[0];
		System.out.println("joining game");
		try {
			String join=DBmanager.getDB().joinGame(game_unique_key,userName);
			if(join.equals("OK")){
				System.out.println("OK");
				response.setStatus(200);
			}else{
				out.write(join);
				response.setStatus(400);
			}
		} catch (SQLException e) {
			e.printStackTrace();
			out.write("we have encountred a technical problem, plz try again later");
			response.setStatus(400);
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
